package com.loyal.camerax.ui.settings

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.viewModels
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.contains
import androidx.navigation.fragment.NavHostFragment
import com.loyal.camerax.R
import com.loyal.camerax.databinding.ActivityCameraSettingsBinding
import com.loyal.camerax.ui.CameraViewModel
import com.loyal.camerax.ui.settings.fragment.GalleryFragment
import com.loyal.camerax.ui.settings.fragment.PhotoFragment
import com.loyal.camerax.utils.ActivityHelper.hideSystemUI
import com.loyal.camerax.utils.MediaStoreUtils
import com.loyal.camerax.utils.PreferenceHelper
import kotlinx.coroutines.launch

class CameraSettingsActivity : AppCompatActivity() {
    private val binding by lazy { ActivityCameraSettingsBinding.inflate(layoutInflater) }
    private val viewModel: CameraViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        onBackPressedDispatcher.addCallback(this, onBackPress)
        //动态显示startDestination，要将app:navGraph="@navigation/nav_config"删除，然后在代码中执行
        val navIdRes = intent.getIntExtra(SETTINGS_ID_RES, -1)
        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.camera_settings_container) as? NavHostFragment?
        val navController = navHostFragment?.navController
        val navGraph = navController?.navInflater?.inflate(R.navigation.nav_camerax_settings)
        navGraph?.let {
            val hasNavIdRes = it.contains(navIdRes)
            if (hasNavIdRes) {
                it.setStartDestination(navIdRes)
                navController.graph = it
            }
        }
        eventCallback()
    }

    private fun eventCallback() {
        viewModel.status.observe(this) {
            //printMessage()
            val current = currentFragment()
            Log.e(TAG, "current=>" + current?.javaClass?.name)
            when (it) {
                223 -> {
                    if (current is GalleryFragment) {
                        lifecycleScope.launch {
                            val mediaList =
                                MediaStoreUtils(this@CameraSettingsActivity).scanImages()
                            current.updateGallery(mediaList)
                        }
                    } else if (current is PhotoFragment) {
                        lifecycleScope.launch {
                            val mediaList =
                                MediaStoreUtils(this@CameraSettingsActivity).scanImages()
                            current.updateGallery(mediaList)
                        }
                    }
                }
            }
        }
    }

    private val onBackPress = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            val intent = viewModel.broadcast.value
            //Log.e(TAG, "handleOnBackPressed: " + (null == intent))
            /*intent?.let {
                LocalBroadcastManager.getInstance(this@CameraSettingsActivity).sendBroadcast(it)
            }*/
            setResult(RESULT_OK, intent)
            finish()
        }
    }

    override fun onResume() {
        super.onResume()
        binding.root.postDelayed({
            hideSystemUI()
        }, IMMERSIVE_FLAG_TIMEOUT)
    }

    private fun printMessage() {
        val navFragment = supportFragmentManager.findFragmentById(R.id.camera_settings_container)
        val fragments = navFragment?.childFragmentManager?.fragments
        Log.e(TAG, "fragment.size" + fragments?.size)
        val fragment =
            navFragment?.childFragmentManager?.primaryNavigationFragment
        Log.e(TAG, "fragment.name=>" + fragment?.javaClass?.name)
    }

    private fun currentFragment(): Fragment? {
        val navFragment = supportFragmentManager.findFragmentById(R.id.camera_settings_container)
        return navFragment?.childFragmentManager?.primaryNavigationFragment
    }

    companion object {
        private const val TAG = "CameraConfigActivity"
        private const val IMMERSIVE_FLAG_TIMEOUT = 500L
        private const val SETTINGS_ID_RES = "settingsIdRes"

        @JvmStatic
        fun launch(
            activity: Activity, launcher: ActivityResultLauncher<Intent>? = null,
            @IdRes settingsIdRes: Int? = -1, orientationMutable: Boolean = false
        ) {
            val intent = Intent(activity, CameraSettingsActivity::class.java)
            intent.putExtra(SETTINGS_ID_RES, settingsIdRes)
            intent.putExtra(PreferenceHelper.MUTABLE_ORIENTATION, orientationMutable)
            if (null == launcher)
                activity.startActivity(intent)
            else launcher.launch(intent)
        }
    }
}
